﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using RMS.Models;

namespace RMS.Pages.Helpers
{
    // Defined an enum called SessionKey that contains values for the type of data we are going to store in the session
    /* There are values for CART (which we will use for the Cart object) and for RETURN_URL 
     * (which we use for the URL that users will be returned to if they click the Continue Shopping button, 
     * ensuring that their category and pagination values will be preserved). */

    public enum SessionKey {
        CART,
        RETURN_URL
    }

    /* Class handles the current web session / cart interactions */

    public static class SessionHelper {

        /*
        The SessionHelper class contains a Set method that will place a new data object into the session state using a
        SessionKey value. The Get<T> method takes a SessionKey value and returns the corresponding data object. The Get
        method has a generic type parameter, which we use to ensure that the expected data type matches the stored type. We
        build on the Get<T> and Set methods to create the GetCart method, which addresses the code duplication issue and
        manages the Cart object for the user in a single place.
        */
        
        public static void Set(HttpSessionState session, SessionKey key, object value) {
            session[Enum.GetName(typeof(SessionKey), key)] = value;
        }

        public static T Get<T>(HttpSessionState session, SessionKey key) {
            object dataValue = session[Enum.GetName(typeof(SessionKey), key)];
            
            if (dataValue != null && dataValue is T) {
                return (T)dataValue;
            }
            else {
                return default(T);
            }
        }

        public static Cart GetCart(HttpSessionState session) {
            Cart myCart = Get<Cart>(session, SessionKey.CART);
            if (myCart == null) {
                myCart = new Cart();
                Set(session, SessionKey.CART, myCart);
            }
            return myCart;
        }
    }
}